layui.config({
    base: '/lib/layuiadmin/' //静态资源所在路径
}).extend({
    index: 'lib/index' //主入口模块
}).use(['index', 'upload'], function() {
    var table = layui.table,
        form = layui.form,
        laydate = layui.laydate,
        upload = layui.upload,
        element = layui.element,
        laytpl = layui.laytpl,
        $ = layui.jquery,
        $addBtn = $('#addBtn'),
        $queryForm = $('#queryForm'),
        url = '/system/user/',
        layerIndex = 1;

    // 绘制表格
    table.render({
// 		id: 'table',
        elem: '#table',
        url: '/system/user/table',
        page: true, // 开始分页
        // cellMinWidth: 80, // 定义全局最小宽度
        request: {
            pageName: 'offset'
        },
        response: {
            statusCode: 10000
            // countName: 'total', //数据总数的字段名称，默认：count
            // dataName: 'list' //数据列表的字段名称，默认：data
        },
        cols: [[
            {type: 'numbers', title: '序号'},
            {field:'account', title: '账号', sort: true},
            {field:'name', title: '姓名'},
            {field:'sexName', title: '性别'},
            {field:'email', title: '邮件'},
            {field:'phone', title: '电话'},
            {field:'createtimeText', title: '创建时间'},
            {field:'status', title: '状态', align:'center', templet: '#status'},
            {fixed: 'right', align:'center', width: 180, toolbar: '#operationBar'}
        ]]
    });
    //监听工具条
    table.on('tool(table)', function(obj) {
        var data = obj.data,
            $this = $(this),
            getView = view.innerHTML,
            getEdit = editForm.innerHTML;
        if(obj.event === 'detail') {
            $.get('/system/user/' + data.id, function(res) {
                if(res.code == 403) {
                    layer.msg(res.message, {icon: 4});
                } else {
                    laytpl(getView).render(res, function(html) {
                        popupWin($this.text(), html, false);
                    })
                }
            })
        } else if(obj.event === 'del') {
            layer.confirm('真的删除行么', {icon: 3}, function(index) {
                operate('DELETE', {'id': data.id}, false, obj);
                layer.close(index);
            });
        } else if(obj.event === 'edit') {
            $.get('/system/user/' + data.id, function(res) {
                if(res.status == 403) {
                    layer.msg(res.message, {icon: 4});
                } else {
                    res.allRoles = allRoles;
                    laytpl(getEdit).render(res, function(html) {
                        popupWin($this.text(), html, true);
                    });
                    rendering();
                }
            })
        }
    });

    // 监听状态改变
    form.on('switch(switchSysUser)', function(obj) {
        operate('PUT', {'id': this.id, 'statusType': obj.elem.checked}, false);
    });

    // 搜索条件提示
    $queryForm.find('input').on('mouseover', function() {
        if(typeof($(this).attr('title')) == 'undefined') return;
        layer.tips($(this).attr('title'), this, {tips: 1});
    })

    // 新增
    form.on('submit(addBtn)', function(data) {
        var $this = $(this);
        laytpl(addForm.innerHTML).render(allRoles, function(html) {
            popupWin($this.attr('title'), html, true);
        });
        rendering();
        return false;
    })

    // 新增用户
    form.on('submit(add)', function(data) {
        var $form = $(this).parents('form');
        var roles = [];
        $form.find('input[name=roles]:checked').each(function() {
            roles.push($(this).val());
        })
        data.field.roles = roles;
        operate('POST', data.field, true);
        return false;
    })

    // 更新
    form.on('submit(update)', function(data) {
        var $form = $(this).parents('form');
        var roles = [];
        $form.find('input[name=roles]:checked').each(function() {
            roles.push($(this).val());
        })
        data.field.roles = roles;
        operate('PUT', data.field, true);
        return false;
    })

    // 查询用户
    form.on('submit(query)', function(data) {
        table.reload('table', {
            where: data.field
        });
        return false;
    })

    // 用户操作
    // ajaxType 请求类型
    // data 参数
    // refresh 是否刷新
    // 删除操作时传入的当前行对象
    function operate(ajaxType, data, refresh, delRow) {
        if(ajaxType == 'DELETE') {
            url = url + data.id;
        }
        $.ajax({
            url: url,
            type: ajaxType,
            async: true,
            data: data,
            success: function(res) {
                if(res.code == 10000) {
                    layer.close(layerIndex);
                    if(refresh) {
                        table.reload('table');
                    } else if(ajaxType == 'DELETE') {
                        delRow.del();
                    }
                    if(data.resetPwd) {
                        layer.alert(res.message, {icon: 6});
                    } else {
                        layer.msg(res.message, {icon: 1});
                    }
                }  else if(res.code == 403) {
                    layer.msg(res.message, {icon: 4});
                } else {
                    layer.msg(res.message, {icon: 5});
                }
            }
        })
    }

    //渲染弹框
    function popupWin(title, content, showBtn) {
        layerIndex = layer.open({
            id: 'meatball',
            type: 1, //Page层类型
            area: '700px', //['700px', '480'],
            maxWidth: 1000,
            maxHeight: 800,
            title: title,
            skin: 'layui-layer-rim', //加上边框
            shade: 0.1, //遮罩透明度
            // maxmin: true, //允许全屏最小化
            anim: 0, //0-6的动画形式，-1不开启
            scrollbar: false, //禁用滚动
            content: content,
            btn: showBtn ? ['<i class="layui-icon layui-icon-ok"></i> 提交', '<i class="layui-icon layui-icon-refresh-1"></i> 重置'] : '',
            yes: function(index, layero) {
                layero.find('form .submit').trigger('click');
                return false;
            },
            btn2: function(index, layero) {
                layero.find('form .reset').trigger('click');
                return false;
            }
        });
        // layer.full(layerIndex);
    }

    // 动态渲染控件
    function rendering() {
        var $form = $('form');
        // 渲染select
        form.render('select');
        // 重新渲染多选框
        form.render('checkbox');
        // 初始化日期
        laydate.render({
            elem: '.birthday'
        });
        // 上传头像
        upload.render({
            elem: '.layui-user-head-img',
            url: '/upload',
            size: 10240, // 限制上传大小
            done: function(res, index, upload) {
                var url = '/image/' + res[0].url;
                $form.find('.layui-user-head-img').attr('src', url);
                $form.find('input[name=avatar]').val(url);
            }
        })
    }
});